import React, { useEffect } from "react";
import TreeItem from "./treeItem";
export interface ITreeData {
  parent_name: string;
  online_status: string;
  children?: ITreeData[];
  tree_name: string;
  is_leaf: string;
  label: string;
  full_path: string;
  key: string;
  pos: string;
  level: number;
  isLeaf: boolean;
  is_open?: boolean;
  isLastChild: any[];
}
// 递归组件
export default function ByTree(props: { treeData: ITreeData[] }) {
  const { treeData } = props;
  const [tree, setTree] = React.useState<ITreeData[]>(treeData);
  useEffect(() => {
    // console.log(treeData);
  }, []);

  function onOpen(pos: string) {
    // console.log(pos);
    // console.log(treeData);
    // 1. 判断 treeData 中是否有 pos
    // 2. 如果有，就把 pos 的 显示隐藏  取反
    treeData.forEach((item) => {
      if (item.pos === pos) {
        // 显示隐藏
        console.log(item);
        item.is_open = !item.is_open;
      }
    });
    setTree([...treeData]);
  }
  return (
    <div>
      {tree.map((item: ITreeData) => {
        return (
          <ul key={item.pos}>
            <TreeItem onOpen={onOpen} {...item} />
            {!item.is_open && item.children && (
              <ByTree treeData={item.children} />
            )}
          </ul>
        );
      })}
    </div>
  );
}
